<template>
	<view>
		<view class="login-container">
			<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
			<button type="primary" class="btn-login" @click="getUserInfo">一键登录</button>
			<view class="tips-text">登录后尽享更多权益</view>
		</view>
	</view>
</template>

<script>
	import {
		mapActions,
		mapState
	} from 'vuex'

	export default {
		name: "my-login",
		data() {
			return {};
		},
		computed: {
			...mapState('m_user', ['redirectInfo']),
		},
		methods: {

			...mapActions('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),

			// 获取微信用户的基本信息
			getUserInfo() {
				uni.getUserProfile({
					desc: '用于完善会员资料',
					success: (res) => {
						this.updateUserInfo(res.userInfo)
						this.getToken(res)
					},
					fail(error) {
						if (error.errMsg === 'getUserProfile:fail auth deny') return uni.$showmessage('您取消了登录授权！')
					}

				})
			},

			async getToken(info) {
				const [err, res] = await uni.login().catch(err => err)
				if (err || res.errMsg !== 'login:ok') return uni.$showmessage('登录失败！')
				// 准备参数对象
				const query = {
					code: res.code,
					encryptedData: info.encryptedData,
					iv: info.iv,
					rawData: info.rawData,
					signature: info.signature
				}

				// 换取 token
				const {
					data: loginResult
				} = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				if (loginResult.meta.status !== 200) return uni.$showmessage('登录失败！')

				// 更新 vuex 中的 token
				this.updateToken(loginResult.message.token)

				// 返回登录之前的页面
				this.navigateBack()
			},
			
			// 返回登录之前的页面
			navigateBack() {
				if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
					uni.switchTab({
						// 要导航到的页面地址
						url: this.redirectInfo.from,
						// 导航成功之后，把 vuex 中的 redirectInfo 对象重置为 null
						complete: () => {
							this.updateRedirectInfo(null)
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.login-container {
		height: 750rpx;
		background-color: #F8F8F8F8;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
		overflow: hidden;

		// 在末尾添加伪元素
		&::after {
			content: '';
			width: 100%;
			height: 40px;
			background-color: white;
			position: absolute;
			bottom: 0;
			left: 0;
			border-radius: 100%;
			transform: translateY(50%);

		}

		.btn-login {
			width: 90%;
			border-radius: 100px;
			margin: 15px 0;
			background-color: #C00000;
		}

		.tips-text {
			font-size: 12px;
			color: gray;
		}
	}
</style>
